import posts from '../utils/postData.js';

const createPostPopup = () => {
  const popup = document.createElement('div');
  popup.classList.add('post-popup');

  const overlay = document.createElement('div');
  overlay.classList.add('overlay');
  overlay.addEventListener('click', () => {
    popup.style.display = 'none';
  });

  const popupContent = document.createElement('div');
  popupContent.classList.add('popup-content');

  const closeButton = document.createElement('button');
  closeButton.textContent = '关闭';
  closeButton.classList.add('close-button');
  closeButton.addEventListener('click', () => {
    popup.style.display = 'none';
  });

  const postCover = document.createElement('img');
  postCover.classList.add('post-cover-popup');

  const postTitle = document.createElement('h2');
  const postDate = document.createElement('p');
  const postContent = document.createElement('p');

  popupContent.appendChild(closeButton);
  popupContent.appendChild(postCover);
  popupContent.appendChild(postTitle);
  popupContent.appendChild(postDate);
  popupContent.appendChild(postContent);

  popup.appendChild(overlay);
  popup.appendChild(popupContent);

  document.body.appendChild(popup);

  return {
    popup,
    postCover,
    postTitle,
    postDate,
    postContent
  };
};

export const setupPostPopup = () => {
  const { popup, postCover, postTitle, postDate, postContent } = createPostPopup();
  const postItems = document.querySelectorAll('.post-item');

  postItems.forEach((item) => {
    item.addEventListener('click', () => {
      const postId = parseInt(item.dataset.postId);
      const post = posts.find((p) => p.id === postId);

      postCover.src = post.coverImage;
      postTitle.textContent = post.title;
      postDate.textContent = `发表于 ${post.publishDate} | 最后修改于 ${post.modifyDate}`;
      postContent.textContent = post.content;

      popup.style.display = 'block';
    });
  });
};
